package de.baumann.browser.activitys.duobao

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.Toast
import de.baumann.browser.R
import de.baumann.browser.activitys.user.BindETHActivity
import de.baumann.browser.adapter.CYJLAdapter
import de.baumann.browser.api.net.vo.duobao.CYJL
import de.baumann.browser.api.net.vo.duobao.DuoBao
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.duobao.IDuoBaoDetailView
import de.baumann.browser.present.duobao.DuoBaoDetailPresenter
import de.baumann.browser.units.GlideImageLoader
import de.baumann.browser.utils.getUser
import de.baumann.browser.utils.web3j.TokenUtil
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.*
import kotlinx.android.synthetic.main.activity_duo_bao_detail.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import java.lang.Exception

class DuoBaoDetailActivity : BaseOdinActivity<IDuoBaoDetailView, DuoBaoDetailPresenter>(), IDuoBaoDetailView {

    companion object {
        fun startDuoBaoDetailActivity(context: Context, id: String, code: String) {
            context.startActivity(Intent(context, DuoBaoDetailActivity::class.java).apply {
                putExtra("id", id)
                putExtra("code", code)
            })
        }
    }


    override fun getLayout(): Int {
        return R.layout.activity_duo_bao_detail
    }

    override fun getTitleText(): String {
        return "${intent.getStringExtra("code")}期"
    }

    override fun getBackIcon(): Int {
        return R.drawable.ic_back
    }

    private var ethWallet: ETHWallet? = null
    private var number = "0"
    private var amount = "0"

    private lateinit var cyjlAdapter: CYJLAdapter
    private var buyDialog: DuoBaoBuyDialog? = null
    override fun initView() {
        initToolbar(commToolBar, commTitle)
        cyjlAdapter = CYJLAdapter()
        cyjlList.adapter = cyjlAdapter
        cyjlAdapter.setOnItemClickListener { adapter, view, position ->
            val jl = cyjlAdapter.getItem(position)
            CanYuDetailActivity.startCanYuDetailActivity(mContext, jl!!.participationInfoId)
        }

        allCanYu.setOnClickListener {
            CanYuRecordActivity.startCanYuRecordActivity(mContext, getId())
        }

        buyNow.setOnClickListener {

            var bindEth = getUser()?.eth_address
            if (bindEth == null) {
                BindEthDialog(mContext, View.OnClickListener {
                    BindETHActivity.startBindETHActivity(mContext, "")
                }).show()
                return@setOnClickListener
            }

            if (bindEth.startsWith("odx")) {
                bindEth = "0${bindEth.substring(2)}"
            }

            val ethWallet = WalletDaoUtils.queryWalletByAddress(bindEth)


            if (ethWallet == null) {
                showShortToast("请导入绑定地址所对应的钱包")
                return@setOnClickListener
            }

            this.ethWallet = ethWallet


            if (duoBao == null) {
                return@setOnClickListener
            }

            buyDialog = DuoBaoBuyDialog(mContext, object : DuoBaoCallBack {
                override fun callback(number: String, jine: String) {
                    this@DuoBaoDetailActivity.number = number
                    amount = jine
                    presenter?.createDuoBaoOrder(number)
                }
            })
            buyDialog!!.setData(duoBao!!)
            buyDialog!!.show()
        }

        dbDetailBanner.setImageLoader(GlideImageLoader())

    }

    override fun initData() {
        presenter?.getDetail()
        presenter?.cyjl()
    }

    override fun createPresenter(): DuoBaoDetailPresenter {
        return DuoBaoDetailPresenter()
    }

    override fun createView(): IDuoBaoDetailView {
        return this
    }

    override fun getId(): String {
        return intent.getStringExtra("id")
    }

    private var duoBao: DuoBao? = null
    override fun setData(data: DuoBao) {
        this.duoBao = data
        setImage(data.imageInfo)
        setTitle(data.name)
        setprice(data.totalValue.toString())
        setMaxProgress(data.partNum)
        setprogress(data.partNum - data.residuePartNum)
        setTotalFene(data.partNum.toString())
        setShengYuFene(data.residuePartNum.toString())
        setStatus(data.operationStatus)
        val bfb = (data.partNum - data.residuePartNum).toDouble() / data.partNum.toDouble()
        setBaiFenBi((bfb * 100).toInt())
    }

    override fun setImage(url: String) {
        val list = if (url.contains(",")) {
            url.split(",")
        } else {
            arrayListOf(url)
        }
        dbDetailBanner.setImages(list)
        dbDetailBanner.start()
    }

    override fun setTitle(title: String) {
        dbDetlMingcheng.text = title
    }

    @SuppressLint("SetTextI18n")
    override fun setprice(price: String) {
        dbJiaGe.text = "价值 $price ODIN"
    }

    override fun setMaxProgress(max: Int) {
        duobaojindu.max = max
    }

    override fun setprogress(progress: Int) {
        duobaojindu.progress = progress
    }

    @SuppressLint("SetTextI18n")
    override fun setBaiFenBi(bfb: Int) {
        dbjinduzhi.text = "进度 $bfb%"
    }

    @SuppressLint("SetTextI18n")
    override fun setTotalFene(total: String) {
        dbZongFene.text = "总需份额 $total 份"
    }

    @SuppressLint("SetTextI18n")
    override fun setShengYuFene(sy: String) {
        dbShengYuFene.text = "剩余 $sy 份"
    }

    override fun setStatus(status: Int) {
        when (status) {
            1, 2 -> {
                istatus.setImageResource(R.drawable.progress)
                buyNow.visibility = View.VISIBLE
            }

            3 -> {
                istatus.setImageResource(R.drawable.prize)
                buyNow.visibility = View.GONE
            }

            5 -> {
                istatus.setImageResource(R.drawable.daikaiqi)
                buyNow.visibility = View.GONE
            }
        }
    }

    private var key = ""
    private var pwdd: PayPwdDialog? = null
    override fun orderCreateSuccess(key: String) {
        if (key.isEmpty()) {
            return
        }

        this.key = key
        pwdd = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
            override fun callback(pwd: String) {
                if (ethWallet == null) {
                    showShortToast("钱包信息获取失败，请重试")
                    return
                }

                try {
                    val privateKey = TokenUtil.getPrivateKey(pwd, ethWallet)
                    presenter.transfer(ethWallet!!.getAddress(), privateKey, amount)
                    pwdd!!.dismiss()
                } catch (e: Exception) {
                    if ("Invalid password provided" == e.message) {
                        Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(mContext, e.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
        pwdd!!.show()
    }

    override fun onError(errorMsgId: Int) {
        if (errorMsgId==500){
            orderCreateFailed("0")
        }
    }

    override fun onError(errorMsg: String?) {

    }

    override fun orderCreateFailed(residue_part_num: String) {
        val fned = FeneNotEnoughDialog(mContext)
        fned.a(residue_part_num)
        fned.show()
    }

    private var hash = ""
    override fun transferSuccess(hash: String) {
        this.hash = hash
        presenter?.confirm(key, getId(), number, hash, amount)
    }

    override fun buySuccess() {
        buyDialog?.dismiss()
        BuySuccessActivity.startBuySuccessActivity(mContext, duoBao!!.phaseNum, amount, number, hash)
    }

    override fun setCYJL(list: List<CYJL>) {
        cyjlAdapter.setNewData(list)
    }
}